import { useNavigate, useLocation } from 'react-router-dom';
import Header from '@/components/header';
import logo from "@/assets/images/logo.svg";
import styles from "./index.module.scss";
import { Form, Button, Toast, Image } from '@douyinfe/semi-ui';
import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { setAuth } from '@/store';
import auth from '@/api/auth';
import { encrypt, decrypt } from '@/utils/jsencrypt';

export default function LoginPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const [formApi, setFormApi] = useState();

  // 组件加载时，从localStorage读取保存的登录信息
  useEffect(() => {
    const savedLoginInfo = localStorage.getItem('loginInfo');
    if (savedLoginInfo && formApi) {
      const { account, password, remember } = JSON.parse(savedLoginInfo);
      if (remember) {
        formApi.setValues({ account, password: decrypt(password), remember });
      }
    }
  }, [formApi]);

  const validateAccount = (value) => {
    if (!value) {
      return '用户名不能为空';
    }
    const trimmedValue = value.trim();
    if (trimmedValue.length < 3) {
      return '用户名长度不能小于3个字符';
    }
    if (!/^[a-zA-Z0-9_]+$/.test(trimmedValue)) {
      return '用户名只能包含字母、数字和下划线';
    }
    return '';
  };

  const validatePassword = (value) => {
    if (!value) {
      return '密码不能为空';
    }
    if (value.length < 6) {
      return '密码长度不能小于6个字符';
    }
    return '';
  };

  const handleSubmit = async (values) => {
    const trimmedAccount = values.account.trim();
    try {
      const response = await auth.login({ account: trimmedAccount, password: values.password });
      // 处理记住账号密码
      if (values.remember) {
        localStorage.setItem('loginInfo', JSON.stringify({
          account: trimmedAccount,
          password: encrypt(values.password),
          remember: true
        }));
      } else {
        localStorage.removeItem('loginInfo');
      }
      dispatch(setAuth({
        token: response.data.token
      }));
      Toast.success({content:'登录成功',stack: true});
      const from = location.state?.from || '/';
      navigate(from, { replace: true });
    } catch (error) {
      console.error('Login error:', error);
    }
  };

  return (
    <div className={styles.loginPage}>
      <Header showLogo={true} cursor={false}/>
      <div className={styles.loginSection}>
        <div className={styles.loginContent}>
          <div className={styles.main}>
            <div className={styles.subSection}>
              <Image
                src={logo}
                preview={false}
                draggable={false}
                className={styles.image}
              />
              <div className={styles.subBlock}>
                <div className={styles.title}>欢迎回来</div>
                <div className={styles.text}>
                  登录AI工作平台账户
                </div>
              </div>
            </div>
            <Form onSubmit={handleSubmit} style={{ width: "100%" }} autoComplete="off" getFormApi={setFormApi}>
              <Form.Input
                field='account'
                label='用户名'
                style={{ width: '100%' }}
                maxLength={30}
                placeholder='输入用户名'
                validate={validateAccount}
                trigger="change"
              />
              <Form.Input
                mode="password"
                field='password'
                maxLength={30}
                label='密码'
                style={{ width: '100%' }}
                placeholder='输入密码'
                validate={validatePassword}
                trigger="change"
              />
              <div style={{display: 'flex',alignItems: 'center',justifyContent: 'space-between'}}>
                <Form.Checkbox field='remember' pure style={{display:"flex",alignItems: "center","padding": `12px 0`}}>记住账号密码</Form.Checkbox>
              </div>
              <Button block htmlType='submit' style={{ background: "var(--button-color)", color: "#fff" }}>
                登录
              </Button>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
}